package com.lf.web.service.system.module;

import com.lf.data.Cluster;
import com.lf.data.ClusterUtil;
import com.lf.data.Validate;
import com.lf.web.service.system.webnode.WebNodeDAO;
import com.lf.data.search.Query;
import com.lf.data.search.Sort;
import com.lf.web.service.ServiceSupport;
import com.lf.web.service.system.webnode.WebNode;
import com.lf.web.service.system.extension.Extension;
import com.lf.web.service.system.extension.ExtensionDAO;
import org.apache.log4j.Logger;

import java.util.List;

public class ModuleEditService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(ModuleEditService.class);
    private ModuleDAO moduledao;
    private ExtensionDAO extensiondao;
    private WebNodeDAO channeldao;

    private String id = "";
    private Module module;
    private Extension extension = new Extension();
    private List<Cluster> channels = null;

    public ModuleEditService() {
    }

    public void setModuledao(ModuleDAO moduledao) {
        this.moduledao = moduledao;
    }

    public void setExtensiondao(ExtensionDAO extensiondao) {
        this.extensiondao = extensiondao;
    }

    public void setChanneldao(WebNodeDAO channeldao) {
        this.channeldao = channeldao;
    }

    private void initParamValue() {
        this.id = form.getString("id");
    }

    public String execute() {
        initParamValue();
        if (Validate.check(Validate.OBJECTID, id)) {
            module = new Module(moduledao.findById(id));
            if (module.isEmpty()) {
                LOGGER.error("非法ID:id=" + id);
                return error(404);
            }
            module.formatOption();
            String extkey = module.getString(Module.EXT_KEY);
            Query query = new Query();
            query.eq(Extension.KEY, extkey);
            extension.putAll(extensiondao.findOne(query));
            if (extension.isEmpty()) {
                return "noExt";
            }
            Sort sort = new Sort();
            sort.desc(WebNode.INDEX);
            channels = channeldao.find(null, null, sort);
        } else {
            LOGGER.error("错误ID：id=" + id);
            return error(404);
        }
        putData();
        return "editview";
    }

    private void putData() {
        context.put("module", module);
        context.put("extension", extension);
        context.put("check", ClusterUtil.getCheck(Module.class));
        context.put("channels", channels);
    }
}
